/**
 * Written By: Nicholas Hillier Nov, 2008
 * 
 * NEEDS REFACTORING
 * 
 * Meant to be used with a form... only new functionality is the ability to 
 * accept a focus
 *  
*/
package com.ghostmonk.form
{	
	import flash.display.*;
	import flash.events.*;
	import flash.text.TextField;
	import flash.ui.Keyboard;

	public class SubmitButton
	{
		private var _submit:Sprite;
		private var _submitFunction:Function;
		private var _stage:Stage;
		private var _label:TextField;
		
		public function get view():Sprite
		{
			return _submit;
		}
		
		public function SubmitButton(button:Sprite, index:int, submitFunction:Function, stage:Stage, label:String)
		{
			_stage = stage;
			_submit = button;
			_submit.mouseChildren = false;
			_submit.tabIndex = index;
			_submitFunction = submitFunction;
			
			_label = _submit.label;
			_label.text = label;
			
			_submit.addEventListener(FocusEvent.FOCUS_IN, onSubmitFocusIn);
			_submit.addEventListener(FocusEvent.FOCUS_OUT, onSubmitFocusOut);
			activate();	
		}
		
		public function activate():void
		{
			_submit.addEventListener(MouseEvent.CLICK, _submitFunction);
			_submit.buttonMode = true;	
		}
		
		public function deactivate():void
		{
			_submit.removeEventListener(MouseEvent.CLICK, _submitFunction);
			_submit.buttonMode = false;	
		}
		
		private function onSubmitFocusOut(e:FocusEvent):void
		{
			_submit.filters = [];
			_submit.graphics.clear();
			_stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
		}
		
		private function onSubmitFocusIn(e:FocusEvent):void
		{
			_submit.filters = [Config.FORM_GLOW];
			_stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
		}
		
		private function onKeyDown(e:KeyboardEvent):void
		{
			if(e.keyCode == Keyboard.ENTER)
			{
				_submitFunction(null);
			}
		}
	}
}